<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 2] 2.4 Hello Web! IV: Netscape's Revenge</TITLE>
<META NAME="author" CONTENT="Pat Niemeyer and Josh Peck">
<META NAME="date" CONTENT="Tue Jul 22 18:48:44 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="Java">
<META NAME="title" CONTENT="Exploring Java">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Exploring Java" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch02_03.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 2<br>A First Applet</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch03_01.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-4">2.4 Hello Web! IV: Netscape's Revenge</A></h2>

<P CLASS=para>
We have explored quite a few features of Java with the first three
versions of the <tt CLASS=literal>HelloWeb</tt> applet. But until now,
our applet has been rather passive; it has waited patiently for events
to come its way and responded to the whims of the user. Now our
applet is going to take some
initiative--<tt CLASS=literal>HelloWeb4</tt> will blink! The code for
our latest version is shown below.

<DIV CLASS=programlisting>
<P>
<PRE>
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class HelloWeb4 extends Applet 
    implements MouseMotionListener, ActionListener, Runnable {
    int messageX = 125, messageY = 95;
    String theMessage;
    Button theButton;
    int colorIndex = 0;
    static Color[] someColors = { 
        Color.black, Color.red, Color.green, Color.blue, Color.magenta };
    Thread blinkThread;
    boolean blinkState;
    public void init() {
        theMessage = getParameter("message");
        theButton = new Button("Change Color");
        add(theButton);
        addMouseMotionListener(this);
        theButton.addActionListener(this);
    }
    
    public void paint( Graphics graphics ) {
        graphics.setColor( blinkState ? Color.white : currentColor() );
        graphics.drawString( theMessage, messageX, messageY );
    }
    public void mouseDragged( MouseEvent e ) {
        messageX = e.getX(); 
        messageY = e.getY();
        repaint();
    }
    public void mouseMoved( MouseEvent e ) { }
    public void actionPerformed( ActionEvent e ) {
        if ( e.getSource() == theButton ) {
            changeColor();
        }
    }
    synchronized private void changeColor() {
        if ( ++colorIndex == someColors.length )
            colorIndex = 0;
        theButton.setForeground( currentColor() );
        repaint();
    }
    synchronized private Color currentColor() {
        return someColors[ colorIndex ];
    }
    public void run() {
        while ( true ) {
            blinkState = !blinkState;
            repaint();
            try {  
                Thread.sleep(500); 
            } catch (Exception e ) { 
                // Handle error condition here...
            }
        }
    }
    public void start() {
        if ( blinkThread == null ) {
            blinkThread = new Thread(this);
            blinkThread.start();
        }
    }
    public void stop() {
        if ( blinkThread != null ) {
            blinkThread.stop();
            blinkThread = null;
        }
    }
}
</PRE>
</DIV>

<P CLASS=para>
If you create <tt CLASS=literal>HelloWeb4</tt> as you have the other
applets and then run it in a Java-enabled Web browser, you'll
see that the text does in fact blink. My apologies if you don't
like blinking text--I'm not overly fond of it
either--but it does make for a simple, instructive example.

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-4.1">Threads</A></h3>

<P CLASS=para>
<A NAME="CH02.THREADS"></A>All the changes we've made in <tt CLASS=literal>HelloWeb4</tt> have
to do with setting up a separate thread of execution to make the text
of our applet blink. Java is a <I CLASS=emphasis>multithreaded</I>
language, which means there can be many threads running at the same
time. A <I CLASS=emphasis>thread</I> is a separate flow of control
within a program. Conceptually, threads are similar to processes,
except that unlike processes, multiple threads share the same address
space, which means that they can share variables and methods (but they
have their own local variables). Threads are also quite lightweight in
comparison to processes, so it's conceivable for a single application
to be running hundreds of threads concurrently.

<P CLASS=para>
Multithreading provides a way for an application to handle many
different tasks at the same time. It's easy to imagine multiple
things going on at the same time in an application like a Web browser.
The user could be listening to an audio clip while scrolling an image,
and in the background the browser is downloading an image.
Multithreading is especially useful in GUI-based applications, as it
can improve the interactive performance of these applications.

<P CLASS=para>
Unfortunately for us, programming with multiple threads can be quite
a headache. The difficulty lies in making sure routines are
implemented so they can be run by multiple concurrent threads.
If a routine changes the value of a state variable, for example, then
only one thread can be executing the routine at a time. Later in this
section, we'll examine briefly the issue of coordinating
multiple thread's access to shared data. In other languages,
synchronization of threads can be an extremely complex and error-prone
endeavor. You'll see that Java gives you a few simple tools that
help you deal with many of these problems. Java threads can be
started, stopped, suspended, and prioritized. Threads are preemptive,
so a higher priority thread can interrupt a lower priority thread when
vying for processor time. See <A HREF="ch06_01.htm">Chapter 6, <i>Threads</i></A> for a
complete discussion of threads.

<P CLASS=para>
The Java run-time system creates and manages a number of threads.
I've already mentioned the AWT thread, which manages
<tt CLASS=literal>repaint()</tt> requests and event processing for
GUI components that belong to the
<tt CLASS=literal>java.awt</tt> package. A Java-enabled Web browser
typically has at least one separate thread of execution it uses to
manage the applets it displays. Until now, our example has done most
of its work from methods of the <tt CLASS=literal>Applet</tt> class, which
means that is has been borrowing time from these threads. Methods like
<tt CLASS=literal>mouseDragged()</tt> and
<tt CLASS=literal>actionPerformed()</tt> are 
invoked by the AWT thread and run on its
time. Similarly, our <tt CLASS=literal>init()</tt> method is called by a
thread in the Web browser. This means we are somewhat limited in the
amount of processing we do within these methods. If we
were, for instance, to go into an endless loop in our
<tt CLASS=literal>init()</tt> method, our applet would never appear, as it
would never finish initializing. If we want an applet to perform any
extensive processing, such as animation, a lengthy calculation, or
communication, we should create separate threads for these tasks.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-4.2">The Thread Class</A></h3>

<P CLASS=para>
As you might have guessed, threads are created and controlled as
<tt CLASS=literal>Thread</tt> objects. We have added a new instance
variable, <tt CLASS=literal>blinkThread</tt>, to our example to hold the
<tt CLASS=literal>Thread</tt> that handles our blinking activity:

<DIV CLASS=programlisting>
<P>
<PRE>
Thread blinkThread; 
</PRE>
</DIV>

<P CLASS=para>
An instance of the <tt CLASS=literal>Thread</tt> class corresponds to a
single thread. It contains methods to start, control, and stop the
thread's execution. Our basic plan is to create a
<tt CLASS=literal>Thread</tt> object to handle our blinking code. We call
the <tt CLASS=literal>Thread</tt>'s <tt CLASS=literal>start()</tt>
method to begin execution. Once the thread starts, it continues to
run until we call the <tt CLASS=literal>Thread</tt>'s
<tt CLASS=literal>stop()</tt> method to terminate it.

<P CLASS=para>
But Java doesn't allow pointers to methods, so how do we tell the
thread which method to run?  Well, the <tt CLASS=literal>Thread</tt>
object is rather picky; it always expects to execute a method called
<tt CLASS=literal>run()</tt> to perform the action of the thread. The
<tt CLASS=literal>run()</tt> method can, however, with a little
persuasion, be located in any class we desire.

<P CLASS=para>
We specify the location of the <tt CLASS=literal>run()</tt> method in
one of two ways. First, the <tt CLASS=literal>Thread</tt> class itself
has a method called <tt CLASS=literal>run()</tt>. One way to execute some
Java code in a separate thread is to subclass
<tt CLASS=literal>Thread</tt> and override its <tt CLASS=literal>run()</tt>
method to do our bidding. In this case, we simply create an instance
of this subclass and call its <tt CLASS=literal>start()</tt> method.

<P CLASS=para>
But it's not always desirable or possible to create a subclass of
<tt CLASS=literal>Thread</tt> to contain our
<tt CLASS=literal>run()</tt> method. In this case, we need to
tell the <tt CLASS=literal>Thread</tt> which object contains the
<tt CLASS=literal>run()</tt> method it should execute. The
<tt CLASS=literal>Thread</tt> class has a constructor that takes
an object reference as its argument. If we create a
<tt CLASS=literal>Thread</tt> object using this constructor and
call its <tt CLASS=literal>start()</tt> method, the
<tt CLASS=literal>Thread</tt> executes the
<tt CLASS=literal>run()</tt> method of the target object, rather
than its own. In order to accomplish this, Java needs to have a
guarantee that the object we are passing it does indeed contain a
compatible <tt CLASS=literal>run()</tt> method. We already
know how to make such a guarantee: we use an interface. Java provides
an interface named <tt CLASS=literal>Runnable</tt> that must be
implemented by any class that wants to become a
<tt CLASS=literal>Thread</tt>.
</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-4.4">The Runnable Interface</A></h3>

<P CLASS=para>
The second technique I described for creating a
<tt CLASS=literal>Thread</tt> object involved passing an object
that implements the <tt CLASS=literal>Runnable</tt> interface to
the <tt CLASS=literal>Thread</tt> constructor. 
The 
<tt CLASS=literal>Runnable</tt> interface specifies that the object
contains a <tt CLASS=literal>run()</tt> method that takes no arguments and
returns no value. This method is called automatically when the system
needs to start the thread. 

<P CLASS=para>
Sticking with our technique for implementing our applet in a single
class, we have opted to add the <tt CLASS=literal>run()</tt> method for
<tt CLASS=literal>blinkThread</tt> to our <tt CLASS=literal>HelloWeb4</tt>
class. This means that <tt CLASS=literal>HelloWeb4</tt> needs to
implement the <tt CLASS=literal>Runnable</tt> interface. We indicate that
the class implements the interface in our class declaration:

<DIV CLASS=programlisting>
<P>
<PRE>
public class HelloWeb4 extends Applet
    implements MouseMotionListener, ActionListener, Runnable {...}
</PRE>
</DIV>

<P CLASS=para>
At compile time, the Java compiler checks to make sure we abide
by this statement. We have carried through by adding an appropriate
<tt CLASS=literal>run()</tt> method to our applet. Our
<tt CLASS=literal>run()</tt> method has the task of changing the color of
our text a couple of times a second. It's a very short routine, but
I'm going to delay looking at it until we tie up some loose ends
in dealing with the <tt CLASS=literal>Thread</tt> itself.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-4.5">start(&nbsp;) and stop(&nbsp;)</A></h3>

<P CLASS=para>
<A NAME="CH02.START"></A><A NAME="CH02.STOP"></A>Now that we know how to create a <tt CLASS=literal>Thread</tt> to execute
our applet's <tt CLASS=literal>run()</tt> method, we need to figure
out where to actually do it. The <tt CLASS=literal>start()</tt> and
<tt CLASS=literal>stop()</tt> methods of the <tt CLASS=literal>Applet</tt>
class are similar to <tt CLASS=literal>init()</tt>. The
<tt CLASS=literal>start()</tt> method is called when an applet is first
displayed. If the user then leaves the Web document or scrolls the
applet off the screen, the <tt CLASS=literal>stop()</tt> method is
invoked. If the user subsequently returns, the
<tt CLASS=literal>start()</tt> method is called again, and so on. Unlike
<tt CLASS=literal>init()</tt>, <tt CLASS=literal>start()</tt> and
<tt CLASS=literal>stop()</tt> can be called repeatedly during the lifetime
of an applet.

<P CLASS=para>
The <tt CLASS=literal>start()</tt> and <tt CLASS=literal>stop()</tt> methods
of the <tt CLASS=literal>Applet</tt> class have absolutely nothing to do
with the <tt CLASS=literal>Thread</tt> object, except that they are a good
place for an applet to start and stop a thread. An applet is
responsible for managing the threads that it creates. It would be
considered rude for an applet to continue such tasks as animation,
making noise, or performing extensive calculations long after it's no
longer visible on the screen. It's common practice, therefore, to
start a thread when an applet becomes visible and stop it when the
applet is no longer visible.

<P CLASS=para>
Here's the <tt CLASS=literal>start()</tt> method from
<tt CLASS=literal>HelloWeb4</tt>:

<DIV CLASS=programlisting>
<P>
<PRE>
public void start() { 
    if ( blinkThread == null ) { 
        blinkThread = new Thread(this); 
        blinkThread.start(); 
    } 
} 
</PRE>
</DIV>

<P CLASS=para>
The method first checks to see if there is an object assigned to
<tt CLASS=literal>blinkThread</tt>; recall that an uninitialized instance
variable has a default value of <tt CLASS=literal>null</tt>. If not, the
method creates a new instance of <tt CLASS=literal>Thread</tt>, passing
the target object that contains the <tt CLASS=literal>run()</tt> method to
the constructor. Since <tt CLASS=literal>HelloWeb4</tt> contains our
<tt CLASS=literal>run()</tt> method, we pass the special variable
<tt CLASS=literal>this</tt> to the constructor to let the thread know
where to find the <tt CLASS=literal>run()</tt> method it should run.
<tt CLASS=literal>this</tt> always refers to our object. Finally, after
creating the new <tt CLASS=literal>Thread</tt>, we call its
<tt CLASS=literal>start()</tt> method to begin execution.

<P CLASS=para>
Our <tt CLASS=literal>stop()</tt> method takes the complimentary position:

<DIV CLASS=programlisting>
<P>
<PRE>
public void stop() { 
    if ( blinkThread != null ) { 
        blinkThread.stop(); 
        blinkThread = null; 
    } 
} 
</PRE>
</DIV>

<P CLASS=para>
This method checks to see if <tt CLASS=literal>blinkThread</tt> is empty.
If not, it calls the thread's <tt CLASS=literal>stop()</tt>
method to terminate its execution. By setting the value of
<tt CLASS=literal>blinkThread</tt> back to <tt CLASS=literal>null</tt>, we
have eliminated all references to the thread object we created in the
<tt CLASS=literal>start()</tt> method, so the garbage collector can
dispose of the object.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-4.6">run(&nbsp;)</A></h3>

<P CLASS=para>
<A NAME="CH02.RUN"></A>Our <tt CLASS=literal>run()</tt> method does its job by setting the value
of the variable <tt CLASS=literal>blinkState</tt>. We have added
<tt CLASS=literal>blinkState</tt>, a <tt CLASS=literal>boolean</tt> value, to
represent whether we are currently blinking on or off:

<DIV CLASS=programlisting>
<P>
<PRE>
boolean blinkState; 
</PRE>
</DIV>

<P CLASS=para>
The <tt CLASS=literal>setColor()</tt> line of our
<tt CLASS=literal>paint()</tt> method has been modified slightly to handle
blinking. The call to <tt CLASS=literal>setColor()</tt> now draws the
text in white when <tt CLASS=literal>blinkState</tt> is
<tt CLASS=literal>true</tt>:

<DIV CLASS=programlisting>
<P>
<PRE>
gc.setColor( blinkState ? Color.white : currentColor() ); 
</PRE>
</DIV>

<P CLASS=para>
Here we are being somewhat terse and using the C-like ternary operator
to return one of two alternate color values based on the value of
<tt CLASS=literal>blinkState</tt>.

<P CLASS=para>
Finally, we come to the <tt CLASS=literal>run()</tt> method itself:

<DIV CLASS=programlisting>
<P>
<PRE>
public void run() { 
    while ( true ) { 
        blinkState = !blinkState; 
        repaint(); 
        try { 
            Thread.sleep(500); 
        } 
        catch (InterruptedException e ) { 
        } 
    } 
} 
</PRE>
</DIV>

<P CLASS=para>
At its outermost level, <tt CLASS=literal>run()</tt> uses an infinite
<tt CLASS=literal>while</tt> loop. This means the method will run
continuously until the thread is terminated by a call to the
controlling <tt CLASS=literal>Thread</tt> object's
<tt CLASS=literal>stop()</tt> method.

<P CLASS=para>
The body of the loop does three things on each pass:

<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>Flips the value of <tt CLASS=literal>blinkState</tt> to its opposite
value using the <tt CLASS=literal>not</tt> operator, <tt CLASS=literal>!</tt>.

<P>
<li CLASS=listitem>Calls <tt CLASS=literal>repaint()</tt> so that our
<tt CLASS=literal>paint()</tt> method can have an opportunity to redraw
the text in accordance with <tt CLASS=literal>blinkState</tt>.

<P>
<li CLASS=listitem>Uses a <tt CLASS=literal>try/catch</tt> statement to trap for an error
in our call to the <tt CLASS=literal>sleep()</tt> method of the
<tt CLASS=literal>Thread</tt> class. <tt CLASS=literal>sleep()</tt> is a
static method of the <tt CLASS=literal>Thread</tt> class. The method can
be invoked from anywhere and has the effect of putting the current
thread to sleep for the specified number of milliseconds. The effect
here is to give us approximately two blinks per second.

<P>
</UL>
</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-4.7">Exceptions</A></h3>

<P CLASS=para>
<A NAME="CH02.TRY"></A><A NAME="CH02.TRY3"></A><A NAME="CH02.TRY2"></A>The <tt CLASS=literal>try/catch</tt> statement in Java is used to handle
special conditions called <I CLASS=emphasis>exceptions</I>. An
exception is a message that is sent, normally in response to an error,
during the execution of a statement or a method. When an exceptional
condition arises, an object is created that contains information about
the particular problem or condition. Exceptions act somewhat like
events. Java stops execution at the place where the exception
occurred, and the exception object is said to be
<I CLASS=emphasis>thrown</I> by that section of code. Like events, an
exception must be delivered somewhere and handled. The section of
code that receives the exception object is said to
<I CLASS=emphasis>catch</I> the exception. An exception causes the
execution of the instigating section of code to abruptly stop and
transfers control to the code that receives the exception object.

<P CLASS=para>
The <tt CLASS=literal>try/catch</tt> construct allows you to catch
exceptions for a section of code. If an exception is caused by a
statement inside of a <tt CLASS=literal>try</tt> clause, Java attempts to
deliver the exception to the appropriate <tt CLASS=literal>catch</tt>
clause. A <tt CLASS=literal>catch</tt> clause looks like a method
declaration with one argument and no return type. If Java finds a
<tt CLASS=literal>catch</tt> clause with an argument type that matches the
type of the exception, that <tt CLASS=literal>catch</tt> clause is
invoked. A <tt CLASS=literal>try</tt> clause can have multiple
<tt CLASS=literal>catch</tt> clauses with different argument types; Java
chooses the appropriate one in a way that is analogous to the
selection of overloaded methods.

<P CLASS=para>
If there is no <tt CLASS=literal>try/catch</tt> clause surrounding the
code, or a matching <tt CLASS=literal>catch</tt> clause is not found, the
exception is thrown up the call stack to the calling method. If the
exception is not caught there, it's thrown up another level, and so
on until the exception is handled. This provides a very flexible
error-handling mechanism, so that exceptions in deeply nested calls
can bubble up to the surface of the call stack for handling. As a
programmer, you need to know what exceptions a particular statement
can generate, so methods in Java are required to declare the
exceptions they can throw. If a method doesn't handle an
exception itself, it must specify that it can throw that exception, so
that the calling method knows that it may have to handle it. See
<A HREF="ch04_01.htm">Chapter 4, <i>The Java Language</i></A> for a complete discussion of exceptions
and the <tt CLASS=literal>try/catch</tt> clause.

<P CLASS=para>
So, why do we need a <tt CLASS=literal>try/catch</tt> clause around our
<tt CLASS=literal>sleep()</tt> call?  What kind of exception can
<tt CLASS=literal>Thread</tt>'s <tt CLASS=literal>sleep()</tt> method
throw and why do we care about it, when we don't seem to check
for exceptions anywhere else?  Under some circumstances,
<tt CLASS=literal>Thread</tt>'s <tt CLASS=literal>sleep()</tt> method
can throw an <tt CLASS=literal>InterruptedException</tt>, indicating that
it was interrupted by another thread. Since the
<tt CLASS=literal>run()</tt> method specified in the
<tt CLASS=literal>Runnable</tt> interface doesn't declare it can
throw an <tt CLASS=literal>InterruptedException</tt>, we must catch it
ourselves, or the compiler will complain. The
<tt CLASS=literal>try/catch</tt> statement in our example has an empty
<tt CLASS=literal>catch</tt> clause, which means that it handles the
exception by ignoring it. In this case, our thread's
functionality is so simple it doesn't matter if it's
interrupted. All of the other methods we have used either handle
their own exceptions or throw only general-purpose exceptions that are
assumed to be possible everywhere and don't need to be explicitly
declared.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-4.8">A Word About Synchronization</A></h3>

<P CLASS=para>
At any given time, there can be a number of threads running in the
Java interpreter. Unless we explicitly coordinate them, these threads
will be executing methods without any regard for what the other
threads are doing. Problems can arise when these methods share the
same data. If one method is changing the value of some variables at
the same time that another method is reading these variables, it's
possible that the reading thread might catch things in the middle and
get some variables with old values and some with new. Depending on
the application, this situation could cause a critical error.

<P CLASS=para>
In our <tt CLASS=literal>HelloWeb</tt> examples, both our
<tt CLASS=literal>paint()</tt> and <tt CLASS=literal>mouseDrag()</tt> methods
access the <tt CLASS=literal>messageX</tt> and <tt CLASS=literal>messageY</tt>
variables. Without knowing the implementation of our particular Java
environment, we have to assume that these methods could conceivably be
called by different threads and run concurrently. 
<tt CLASS=literal>paint()</tt> could be called while
<tt CLASS=literal>mouseDrag()</tt> is in the midst of updating
<tt CLASS=literal>messageX</tt> and <tt CLASS=literal>messageY</tt>. At that
point, the data is in an inconsistent state and if
<tt CLASS=literal>paint()</tt> gets lucky, it could get the new x value
with the old y value. Fortunately, in this case, we probably would
not even notice if this were to happen in our application. We did,
however, see another case, in our <tt CLASS=literal>changeColor()</tt> and
<tt CLASS=literal>currentColor()</tt> methods, where there is the
potential for a more serious "out of bounds" error to
occur.

<P CLASS=para>
The <tt CLASS=literal>synchronized</tt> modifier tells Java to acquire a
<I CLASS=emphasis>lock</I> for the class that contains the method
before executing that method. Only one method can have the lock on a
class at any given time, which means that only one synchronized method
in that class can be running at a time. This allows a method to alter
data and leave it in a consistent state before a concurrently running
method is allowed to access it. When the method is done, it releases
the lock on the class.

<P CLASS=para>
Unlike synchronization in other languages, the
<tt CLASS=literal>synchronized</tt> keyword in Java provides locking at
the language level. This means there is no way that you can
forget to unlock a class. Even if the method throws an exception or
the thread is terminated, Java will release the lock. This feature
makes programming with threads in Java much easier than in other
languages. See <A HREF="ch06_01.htm">Chapter 6, <i>Threads</i></A> for more details on
coordinating threads and shared data.

<P CLASS=para>
Whew! Now it's time to say goodbye to
<tt CLASS=literal>HelloWeb</tt>. I hope that you have developed a feel
for the major features of the Java language, and that this will help
you as you go on to explore the details of programming with Java.

</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch02_03.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch03_01.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Hello Web! III: The Button Strikes!</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>Tools of the Trade</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
